import { onMounted, onUnmounted } from '@vue/composition-api'
import getCurrentComponent from '@/utils/get-current-component'

function onPageScroll(event) {
  const pages = getCurrentPages()
  const page: any = pages[pages.length - 1]
  const { __ONPAGESCROLL_HOOKS__ = [] } = page

  __ONPAGESCROLL_HOOKS__.forEach((scroller) => {
    if (typeof scroller === 'function') {
      // @ts-ignore
      scroller(event)
    }
  })
}

export function usePageScroll(scroller) {
  onMounted(() => {
    const pages = getCurrentPages()
    const page: any = pages[pages.length - 1]
    const vm = getCurrentComponent()

    if (Array.isArray(page.__ONPAGESCROLL_HOOKS__)) {
      page.__ONPAGESCROLL_HOOKS__.push(scroller.bind(vm))
    } else {
      page.__ONPAGESCROLL_HOOKS__ =
        typeof page.onPageScroll === 'function'
          ? [page.onPageScroll.bind(page), scroller.bind(vm)]
          : [scroller.bind(vm)]
    }

    page.onPageScroll = onPageScroll
  })

  onUnmounted(() => {
    let _a
    const pages = getCurrentPages()
    const page: any = pages[pages.length - 1]

    if (page) {
      page.__ONPAGESCROLL_HOOKS__ =
        ((_a = page.__ONPAGESCROLL_HOOKS__) === null || _a === void 0
          ? void 0
          : _a.filter((item) => item !== scroller)) || []
    }
  })
}
